昨天建立好Promethues之後, 今天就可以用python FastAPI框架來建立被監控的網站囉~
其實我昨天已經偷偷寫在docker裡面啦就是onlineweb~如果不做就拿掉被監控的目標物就行哈哈哈
├── Dockerfile
├── docker-compose.yml
├── k8s.yaml # 之前介紹minikube就是用這個專案啦~有沒有這個檔案都不影響
├── main.py
├── requirements.txt
└── utils
├── app.py
├── data.py
└── templates
└── index.html
REQUEST_TIME = Summary('request_processing_seconds', 'Time spent processing request')
Promethues的四大功能 Summary, Counter, Gauge, Histogram詳細使用方法請參考官方文件
# -*- coding: utf-8 -*-
"""
服務主入口
"""
from pathlib import Path
from fastapi.templating import Jinja2Templates
from pathlib import Path
from typing import Optional
from fastapi import (
FastAPI, APIRouter, Request, HTTPException
)
from fastapi.responses import JSONResponse, HTMLResponse
from utils.data import getProduct
from prometheus_client import Counter, Summary
app = FastAPI()
## 路徑問題
BASE_DIR = Path(__file__).resolve().parent
templates = Jinja2Templates(directory=str(Path(BASE_DIR, 'templates')))
## Prometheus 監測數據 這邊可以自己設定跟說明
REQUEST_TIME = Summary('request_processing_seconds', 'Time spent processing request')
REQUEST_COUNT = Counter('request_count', 'Total webapp request count')
LATENCY = Summary('request_processing_latency_seconds', 'Time for a request')
router = APIRouter()
def reply_response(
code: int, desc: str, result: Optional[dict] = None):
msg = {
'Result':result,
'Status': {
'Code': code,
'Desc':desc
}
}
return msg
@REQUEST_TIME.time()
@LATENCY.time()
@router.get(f'/pageList', response_class=JSONResponse)
async def pageList(request: Request):
try:
# 這邊是去跟資料庫互動拉資料出來
data = getProduct()
msg = reply_response(
result = data,
code = 200,
desc = '呼叫成功'
)
return JSONResponse(status_code=200, content=msg)
except:
msg = reply_response(
result = None,
code = 400,
desc='呼叫失敗'
)
return JSONResponse(status_code=400, content=msg)
#跳轉至Index畫面
@router.get(f"/page", response_class=HTMLResponse)
async def userpage(request: Request):
return templates.TemplateResponse("index.html",{"request": request})
# -*- coding: utf-8 -*-
"""
與資料庫做互動
"""
from pymongo import MongoClient
client = MongoClient(
host='localhost:27017', username='帳號', password='密碼')
db = client['Web']
def getProduct():
data = list(db.productList.find({},{'_id':0, 'created_at':0, 'modified_at':0}))
return data
<script type="text/javascript">
$(document).ready( function () {
$.ajax({
url: '/pageList',
type: 'GET',
dataType: 'json',
contentType: 'application/json;',
success: function(data) {
$('#tableObj').DataTable({
"data": data.Result,
"columns": [
//列的標題一般是從DOM中讀取
//也可以使用這個屬性為表格創建列標題
{ data: 'Id', title: "商品編號" },
{ data: 'name', title: "商品名稱" },
{ data: 'channel', title: "通路別" }
]
})
},
error: function(jqXHR, textStatus, errorThrown){
alert('Error: ' + textStatus + ' - ' + errorThrown);
}
});
});
</script>
服務啟動後,打開頁面就會看到監控的數據囉,這些數據就會對應回prometheus裡面的數據
程式碼請參考我的Github